//
//  NetworkManager.m
//  zhangjiantest2
//
//  Created by ZJL on 2024/7/5.
//

#import "NetworkManager.h"

@implementation NetworkManager
+ (void)sendRequestWithURL:(NSURL *)url body:(NSData *)data completion:(completion)completion
{
    NSURLSession *session = [NSURLSession sharedSession];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [request setValue:@"application/octet-stream/json" forHTTPHeaderField:@"Content-Type"];
    [request setHTTPMethod:@"POST"];
    [request setTimeoutInterval: 600];
    [request setValue:@"*/*" forHTTPHeaderField:@"Accept"];
    [request setValue:@"gzip, deflate, br, zstd" forHTTPHeaderField:@"Accept-Encoding"];
    [request setValue:@"zh-CN,zh;q=0.9" forHTTPHeaderField:@"Accept-Language"];
    [request setValue:@"keep-alive" forHTTPHeaderField:@"Connection"];
    [request setValue:@"text/plain;charset=UTF-8" forHTTPHeaderField:@"Content-Type"];
    [request setValue:@"127.0.0.1:21325" forHTTPHeaderField:@"Host"];
    [request setValue:@"https://suite.trezor.io" forHTTPHeaderField:@"Origin"];
    [request setValue:@"empty" forHTTPHeaderField:@"Sec-Fetch-Dest"];
    [request setValue:@"cors" forHTTPHeaderField:@"Sec-Fetch-Mode"];
    [request setValue:@"cross-site" forHTTPHeaderField:@"Sec-Fetch-Site"];
    [request setValue:@"trezor client" forHTTPHeaderField:@"User-Agent"];
    [request setValue:@"\"Not/A)Brand\";v=\"8\", \"Chromium\";v=\"126\", \"Google Chrome\";v=\"126\"" forHTTPHeaderField:@"sec-ch-ua"];
    [request setValue:@"?0" forHTTPHeaderField:@"sec-ch-ua-mobile"];
    [request setValue:@"\"macOS\"" forHTTPHeaderField:@"sec-ch-ua-platform"];

    
    [request setHTTPBody:data];
    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (completion) {
           completion(data, error,response);
        }
    }];
    [dataTask resume];
}


//+ (completion *)sendRequestWithURL2:(NSURL *)url body:(NSData *)data
//{
//    NSURLSession *session = [NSURLSession sharedSession];
//    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
//    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
//    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
//    [request setValue:@"application/octet-stream/json" forHTTPHeaderField:@"Content-Type"];
//    [request setHTTPMethod:@"POST"];
//    [request setTimeoutInterval: 600];
//    [request setValue:@"*/*" forHTTPHeaderField:@"Accept"];
//    [request setValue:@"gzip, deflate, br, zstd" forHTTPHeaderField:@"Accept-Encoding"];
//    [request setValue:@"zh-CN,zh;q=0.9" forHTTPHeaderField:@"Accept-Language"];
//    [request setValue:@"keep-alive" forHTTPHeaderField:@"Connection"];
//    [request setValue:@"text/plain;charset=UTF-8" forHTTPHeaderField:@"Content-Type"];
//    [request setValue:@"127.0.0.1:21325" forHTTPHeaderField:@"Host"];
//    [request setValue:@"https://suite.trezor.io" forHTTPHeaderField:@"Origin"];
//    [request setValue:@"empty" forHTTPHeaderField:@"Sec-Fetch-Dest"];
//    [request setValue:@"cors" forHTTPHeaderField:@"Sec-Fetch-Mode"];
//    [request setValue:@"cross-site" forHTTPHeaderField:@"Sec-Fetch-Site"];
//    [request setValue:@"trezor client" forHTTPHeaderField:@"User-Agent"];
//    [request setValue:@"\"Not/A)Brand\";v=\"8\", \"Chromium\";v=\"126\", \"Google Chrome\";v=\"126\"" forHTTPHeaderField:@"sec-ch-ua"];
//    [request setValue:@"?0" forHTTPHeaderField:@"sec-ch-ua-mobile"];
//    [request setValue:@"\"macOS\"" forHTTPHeaderField:@"sec-ch-ua-platform"];
//    NSString *responseString;
//    
//    // Create a semaphore
//    dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
//    __block NSData *responseData = nil;
//    __block NSError *responseError = nil;
//    __block NSInteger responseStatusCode = 0;
//
//    [request setHTTPBody:data];
//    
//    completion completionBlock = ^(NSData *data,NSError *error,NSURLResponse *response){
//        if(error){
//            
//        }else{
//
//        }
//    };
////
//    
//    
//    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
////        if (completion) {
////           completion(data, error,response);
////
//        completionBlock(data,error,response);
//        
//        // Signal the semaphore to unblock
//        dispatch_semaphore_signal(semaphore);
//
//    }];
//    [dataTask resume];
//    
//    // Wait for the semaphore
//    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
//    
//    
//    return &completionBlock;
//    // Process the response data after the semaphore has been signaled
////    if (responseError) {
////        // Handle the error
////        NSLog(@"Error: %@", responseError.localizedDescription);
////        return nil;
////    } else {
////        if (responseStatusCode == 200) {
////            // Process the successful response
////            NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
////            NSLog(@"Response data: %@", responseString);
////            return responseString;
////        } else {
////            // Handle the failure response
////            NSLog(@"Failed with status code: %ld", (long)responseStatusCode);
////            return nil;
////        }
////    }
//}
//
//
////        if (completion) {
- (NSData *)syncFetchDataFromURL:(NSURL *)url {
    // 创建一个信号量，初始计数为0
    dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
   __block NSData *responseData = nil;
    
    // 创建一个Block来处理数据
    void (^completion)(NSData *) = ^(NSData *data) {
        responseData = data;
        // 信号量计数加1，允许等待线程继续执行
        dispatch_semaphore_signal(semaphore);
    };
    
    // 异步请求数据
    NSURLSessionDataTask *dataTask = [[NSURLSession sharedSession] dataTaskWithURL:url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        if (error == nil) {
            completion(data);
        } else {
            NSLog(@"Error fetching data: %@", error);
            // 如果出现错误，也必须释放信号量
            dispatch_semaphore_signal(semaphore);
        }
    }];
    [dataTask resume];
    
    // 等待信号量计数变为非零，即等待异步请求完成
    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
    
    // 释放信号量
    dispatch_release(semaphore);
    
    return responseData;
}


+ (NSData *)sendRequestWithURL2:(NSURL *)url body:(NSData *)data
    {
        NSURLSession *session = [NSURLSession sharedSession];
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
        [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
        [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
        [request setValue:@"application/octet-stream/json" forHTTPHeaderField:@"Content-Type"];
        [request setHTTPMethod:@"POST"];
        [request setTimeoutInterval: 600];
        [request setValue:@"*/*" forHTTPHeaderField:@"Accept"];
        [request setValue:@"gzip, deflate, br, zstd" forHTTPHeaderField:@"Accept-Encoding"];
        [request setValue:@"zh-CN,zh;q=0.9" forHTTPHeaderField:@"Accept-Language"];
        [request setValue:@"keep-alive" forHTTPHeaderField:@"Connection"];
        [request setValue:@"text/plain;charset=UTF-8" forHTTPHeaderField:@"Content-Type"];
        [request setValue:@"127.0.0.1:21325" forHTTPHeaderField:@"Host"];
        [request setValue:@"https://suite.trezor.io" forHTTPHeaderField:@"Origin"];
        [request setValue:@"empty" forHTTPHeaderField:@"Sec-Fetch-Dest"];
        [request setValue:@"cors" forHTTPHeaderField:@"Sec-Fetch-Mode"];
        [request setValue:@"cross-site" forHTTPHeaderField:@"Sec-Fetch-Site"];
        [request setValue:@"trezor client" forHTTPHeaderField:@"User-Agent"];
        [request setValue:@"\"Not/A)Brand\";v=\"8\", \"Chromium\";v=\"126\", \"Google Chrome\";v=\"126\"" forHTTPHeaderField:@"sec-ch-ua"];
        [request setValue:@"?0" forHTTPHeaderField:@"sec-ch-ua-mobile"];
        [request setValue:@"\"macOS\"" forHTTPHeaderField:@"sec-ch-ua-platform"];
        NSString *responseString;

        [request setHTTPBody:data];
    // 创建一个信号量，初始计数为0
    dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
   __block NSData *responseData = nil;
    
    // 创建一个Block来处理数据
    void (^completion)(NSData *) = ^(NSData *data0) {
        responseData = data0;
        // 信号量计数加1，允许等待线程继续执行
        dispatch_semaphore_signal(semaphore);
    };
    
    // 异步请求数据
    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        if (error == nil) {
            completion(data);
        } else {
            NSLog(@"Error fetching data: %@", error);
            // 如果出现错误，也必须释放信号量
            dispatch_semaphore_signal(semaphore);
        }
    }];
    [dataTask resume];
    
    // 等待信号量计数变为非零，即等待异步请求完成
    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
    
    // 释放信号量
    dispatch_release(semaphore);
    
    return responseData;
}
@end
